/*
 * Copyright 2008 CSC Consulting Group under the Apache License, 
 * Version 2.0 (the "License"); you may not use this file except in 
 * compliance with the License. You may obtain a copy of the License at 
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable 
 * law or agreed to in writing, software distributed under the License is 
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language 
 * governing permissions and limitations under the License.
 */
package com.waw.journal.plugin.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import com.jivesoftware.base.Log;
import com.jivesoftware.base.User;
import com.jivesoftware.base.UserManager;
import com.jivesoftware.base.UserNotFoundException;
import com.jivesoftware.community.*;
import com.jivesoftware.community.action.JiveActionSupport;

import com.waw.journal.plugin.PluginUtils;
import com.waw.journal.plugin.JournalConsts;

/**
 * This action class supports the Journal administration page.
 * In particular, the page allows the administrator to perform two functions:
 * <ul>
 * <li>See the users who need to have Fitness Journal Accounts created for them and to update their profiles
 * 	  with the account information.
 * <li>Set the profile fields to use for:
 * 	<ul>
 * 	<li>Fitness Journal Username
 * 	<li>Fitness Journal Password
 * 	<li>Fitness Journal Autologin
 * 	</ul>
 * </ul>
 * <p>
 * In support of the field settings, the class provides a set of methods that return profile field of different
 * types (e.g., Boolean, Text).
 */
public class JournalAdminAction extends JiveActionSupport {

	private static final long serialVersionUID = 1L;
	private String userNameField = "";
	private String passwordField = "";
	private String autoLoginField = "";
	
	/** Getter for the userNameField property */
	public String getUserNameField() {
		return userNameField;
	}

	/** Setter for the userNameField property */
	public void setUserNameField(String userNameField) {
		this.userNameField = userNameField;
	}

	/** Getter for the passwordField property */
	public String getPasswordField() {
		return passwordField;
	}

	/** Setter for the passwordField property */
	public void setPasswordField(String passwordField) {
		this.passwordField = passwordField;
	}

	/** Getter for the autoLoginField property */
	public String getAutoLoginField() {
		return autoLoginField;
	}

	/** Setter for the AutoLoginField property */
	public void setAutoLoginField(String autoLoginField) {
		this.autoLoginField = autoLoginField;
	}
	
	/**
	 * This method returns the users needing Fitness Journal Accounts.
	 * This is determined by inspecting theUser's extended property for the journal username.
	 * If that field does not exist or has an empty string, the user needs a Fitness Journal Account.
	 * <p>
	 * The username profile field  is only setable by the administrator and is the way the administrator
	 * controls the user's login into Fitness Journal.
	 * 
	 * @return an Iterator ov UserNeedAccount JavaBeans holoding the users that need accounts.
	 */
	public Iterator<UserNeedAccount> getUsersNeedingAccounts()
	{
		ArrayList<UserNeedAccount> list = new ArrayList<UserNeedAccount>();
		UserManager uMan = PluginUtils.getUserManager();
		
		// iterate over the list of users looking for those with no journal.username property.
		Iterator<User> uIter = uMan.users().iterator();
		while(uIter.hasNext())
		{			
			try {
				User user = uMan.getUser(uIter.next().getID());
				Map<String,String> properties = user.getProperties();
				String username = properties.get(JournalConsts.USER_JOURNAL_USERNAME);
				if(user.isEnabled() && (username == null || username.length() == 0))
				{
					UserNeedAccount una = new UserNeedAccount();
					una.setID(Long.toString(user.getID()));
					una.setName(user.getName());
					list.add(una);			
				}
			} catch (UserNotFoundException e) {
					Log.error("JournalAdminAction: A user was not found in the system." );
			}
		}
		return list.iterator();
	}
	
	
	/**
	 * Returns all the Profile Fields defined in the system.
	 * @return an Iterator of ProfileField.
	 */
	public Iterator<ProfileField> getProfileFields()
	{
		ProfileFieldManager pMan = PluginUtils.getProfileFieldManager();
		return pMan.getProfileFields().iterator();
	}
	
	/**
	 * Returns all the Text Profile Fields defined in the system.
	 * @return an Iterator of ProfileField.
	 */
	public Iterator<ProfileField> getTextProfileFields()
	{
		ProfileFieldManager pMan = PluginUtils.getProfileFieldManager();
		ArrayList<ProfileField> retArray = new ArrayList<ProfileField>();
		Iterator<ProfileField> iter = pMan.getProfileFields().iterator();
		while(iter.hasNext())
		{
			ProfileField field = iter.next();
			if(field.getType() == ProfileField.Type.LARGETEXT || field.getType() == ProfileField.Type.TEXT)
				retArray.add(field);
		}
		return retArray.iterator();
	}
	
	/**
	 * Returns all the Boolean Profile Fields defined in the system.
	 * @return an Iterator of ProfileField.
	 */
	public Iterator<ProfileField> getBooleanProfileFields()
	{
		ProfileFieldManager pMan = PluginUtils.getProfileFieldManager();
		ArrayList<ProfileField> retArray = new ArrayList<ProfileField>();
		Iterator<ProfileField> iter = pMan.getProfileFields().iterator();
		while(iter.hasNext())
		{
			ProfileField field = iter.next();
			if(field.getType() == ProfileField.Type.BOOLEAN)
				retArray.add(field);
		}
		return retArray.iterator();
	}
	
    /**
     * This execute method takes the profile field settings and writes them to the Global context.
     * 
     * @see com.jivesoftware.community.action.JiveActionSupport#execute()
     */
    public String execute() {
    	
    	if (getUserNameField() != null && !getUserNameField().equals(""))
    		JiveGlobals.setJiveProperty(JournalConsts.JOURNAL_USERNAME_FIELD,getUserNameField());
    	if(getPasswordField() != null && !getPasswordField().equals(""))
    		JiveGlobals.setJiveProperty(JournalConsts.JOURNAL_PASSWORD_FIELD, getPasswordField());
    	if(getAutoLoginField() != null && !getAutoLoginField().equals(""))
    		JiveGlobals.setJiveProperty(JournalConsts.JOURNAL_AUTOLOGIN_FIELD, getAutoLoginField());
    	
        return SUCCESS;
    }



}
